package com.yingxue.lesson.service.impl;

import com.yingxue.lesson.contants.Constant;
import com.yingxue.lesson.entity.SysDept;
import com.yingxue.lesson.entity.SysUser;
import com.yingxue.lesson.exception.BusinessException;
import com.yingxue.lesson.exception.code.BaseResponseCode;
import com.yingxue.lesson.mapper.SysDeptMapper;
import com.yingxue.lesson.mapper.SysUserMapper;
import com.yingxue.lesson.service.DeptService;
import com.yingxue.lesson.service.RedisService;
import com.yingxue.lesson.utils.CodeUtil;
import com.yingxue.lesson.vo.req.DeptAddReqVO;
import com.yingxue.lesson.vo.req.deptVo.DeptUpdateReqVO;
import com.yingxue.lesson.vo.resp.DeptRespNodeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class DeptServiceImpl implements DeptService {

    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询所有部门
     */
    @Override
    public List<SysDept> selectAll() {
        List<SysDept> depts=deptMapper.selectAll();
        for (SysDept dept: depts) {
            SysDept parent = deptMapper.selectByPrimaryKey(dept.getPid());
            if(parent!=null){
                dept.setPidName(parent.getName());
            }
        }
        return depts;
    }

    /**
     * 查询部门--树形展示
     * 如果传有 deptId 过来就表示部门编辑功能需要排除自己和它的子集叶子节点
     */
    @Override
    public List<DeptRespNodeVO> deptTreeList(String deptId) {
        List<SysDept> depts = deptMapper.selectAll();
        //如果传有 deptId 过来就表示部门编辑功能需要排除自己和它的子集叶子节点
        if (!StringUtils.isEmpty(deptId) && !depts.isEmpty()){
            for (SysDept d : depts) {
                if (d.getId().equals(deptId)){
                    depts.remove(d);
                    break;
                }
            }
        }
        //默认加一个顶级方便新增顶级部门
        DeptRespNodeVO vo = new DeptRespNodeVO();
        vo.setId("0");
        vo.setTitle("顶级部门");
        vo.setSpread(true);
        vo.setChildren(getTree(depts));
        //把vo封装进集合返回
        List<DeptRespNodeVO> list = new ArrayList<>();
        list.add(vo);
        return list;
    }

    /**
     * 递归遍历部门
     */
    public List<DeptRespNodeVO> getTree(List<SysDept> all){

        List<DeptRespNodeVO> list = new ArrayList<>();
        //遍历入口
        for (SysDept sysDept:all) {
            if (sysDept.getPid().equals("0")){
                DeptRespNodeVO respNodeVO = new DeptRespNodeVO();
                respNodeVO.setId(sysDept.getId());
                respNodeVO.setTitle(sysDept.getName());
                respNodeVO.setChildren(getChild(sysDept.getId(),all));
                list.add(respNodeVO);
            }
        }
        return list;
    }

    public List<DeptRespNodeVO> getChild(String id,List<SysDept> all){

        List<DeptRespNodeVO> list = new ArrayList<>();
        //遍历出口
        for (SysDept sysDept:all) {
            if (sysDept.getPid().equals(id)){
                DeptRespNodeVO respNodeVO = new DeptRespNodeVO();
                respNodeVO.setId(sysDept.getId());
                respNodeVO.setTitle(sysDept.getName());
                respNodeVO.setChildren(getChild(sysDept.getId(),all));
                list.add(respNodeVO);
            }
        }
        return list;
    }




//    @Override
//    public List<DeptRespNodeVO> deptTreeList(String deptId) {
//        List<SysDept> list=deptMapper.selectAll();
//        //我要想去掉这个部门的叶子节点，直接在数据源移除这个部门就可以了
//        if(!StringUtils.isEmpty(deptId)&&!list.isEmpty()){
//            for (SysDept s:
//                    list) {
//                if(s.getId().equals(deptId)){
//                    list.remove(s);
//                    break;
//                }
//            }
//        }
//        DeptRespNodeVO respNodeVO=new DeptRespNodeVO();
//        respNodeVO.setId("0");
//        respNodeVO.setTitle("默认顶级部门");
//        respNodeVO.setChildren(getTree(list));
//        List<DeptRespNodeVO> result=new ArrayList<>();
//        result.add(respNodeVO);
//        return result;
//    }
//
//    private List<DeptRespNodeVO> getTree(List<SysDept> all){
//        List<DeptRespNodeVO> list=new ArrayList<>();
//        for (SysDept s: all) {
//            if(s.getPid().equals("0")){
//                DeptRespNodeVO respNodeVO=new DeptRespNodeVO();
//                respNodeVO.setId(s.getId());
//                respNodeVO.setTitle(s.getName());
//                respNodeVO.setChildren(getChild(s.getId(),all));
//                list.add(respNodeVO);
//            }
//        }
//        return list;
//    }
//
//    private List<DeptRespNodeVO> getChild(String id,List<SysDept> all){
//        List<DeptRespNodeVO> list=new ArrayList<>();
//        for (SysDept s : all) {
//            if(s.getPid().equals(id)){
//                DeptRespNodeVO deptRespNodeVO=new DeptRespNodeVO();
//                deptRespNodeVO.setId(s.getId());
//                deptRespNodeVO.setTitle(s.getName());
//                deptRespNodeVO.setChildren(getChild(s.getId(),all));
//                list.add(deptRespNodeVO);
//
//            }
//        }
//        return list;
//    }


    /**
     * 添加部门
     */
    @Override
    public SysDept addDept(DeptAddReqVO vo) {

        String relationCode;
        long result = redisService.incrby(Constant.DEPT_CODE_KEY, 1);
        String deptCode = CodeUtil.deptCode(String.valueOf(result),6,"0");
        SysDept patent = deptMapper.selectByPrimaryKey(vo.getPid());
        if (vo.getPid().equals("0")){
            relationCode=deptCode;
        }
        else if (patent == null){
           log.error("传入的 pid:{}不合法",vo.getPid());
           throw new BusinessException(BaseResponseCode.DATA_ERROR);
        }
        else {
            relationCode= patent.getRelationCode()+deptCode;
        }
        SysDept sysDept = new SysDept();
        BeanUtils.copyProperties(vo,sysDept);
        sysDept.setId(UUID.randomUUID().toString());
        sysDept.setCreateTime(new Date());
        sysDept.setDeptNo(deptCode);
        sysDept.setRelationCode(relationCode);
        int i = deptMapper.insertSelective(sysDept);
        if (i != 1){
            throw new BusinessException(BaseResponseCode.OPERATION_ERROR);
        }
        return sysDept;

    }


    /**
     * 更新部门
     */
    @Override
    public void updateDept(DeptUpdateReqVO vo) {
        //1.查询更新部门
        SysDept sysDept = deptMapper.selectByPrimaryKey(vo.getId());
        if (sysDept == null){
            log.error("传入 的 id:{}不合法",vo.getId());
            throw new BusinessException(BaseResponseCode.DATA_ERROR);
        }
        //2.更新部门
        SysDept updateDept = new SysDept();
        BeanUtils.copyProperties(vo,updateDept);
        updateDept.setUpdateTime(new Date());
        int i = deptMapper.updateByPrimaryKeySelective(updateDept);
        if (i!=1){
            throw new BusinessException(BaseResponseCode.OPERATION_ERROR);
        }
        //3.维护层级
        //说明层级发生了变化
        if (!vo.getPid().equals(sysDept.getPid())){
            SysDept newParent = deptMapper.selectByPrimaryKey(vo.getPid());
            if (!vo.getPid().equals("0") && newParent==null){
                log.error("传入 的 pid:{}不合法",vo.getId());
                throw new BusinessException(BaseResponseCode.DATA_ERROR);
            }
            //查询 旧部门
            SysDept oldParent = deptMapper.selectByPrimaryKey(sysDept.getPid());
            String oldRelationCode;
            String newRelationCode;

           // 根目录降到其他目录
            if (sysDept.getPid().equals("0")){
                oldRelationCode=sysDept.getRelationCode();
                newRelationCode=newParent.getRelationCode()+sysDept.getId();
                // 其他目录降到根目录
            }else if (vo.getPid().equals("0")){
                oldRelationCode=sysDept.getRelationCode();
                newRelationCode=sysDept.getDeptNo();
            }else {
                oldRelationCode=oldParent.getRelationCode();
                newRelationCode=newParent.getRelationCode();
            }
            //去更新
            int count = deptMapper.updateRelationCode(oldRelationCode,newRelationCode,sysDept.getRelationCode());
            if (count!=1){
                throw new BusinessException(BaseResponseCode.DATA_ERROR);
            }


        }



    }


    /**
     * 删除部门
     */
    @Override
    public void deletedDept(String id) {
        SysDept sysDept = deptMapper.selectByPrimaryKey(id);
        if (sysDept==null){
            log.info("传入的部门id在数据库不存在{}",id);
            throw new BusinessException(BaseResponseCode.DATA_ERROR);
        }
        //1.查找它和它的叶子节点
        List<String> ids = deptMapper.selectChildIds(sysDept.getRelationCode());

        //2.判断它和它子集的叶子节点是否关联有用户
        List<SysUser> sysUsers = sysUserMapper.selectUserInfoByDeptIds(ids);
        if (!sysUsers.isEmpty()){
            throw new BusinessException(BaseResponseCode.NOT_PERMISSION_DELETED_DEPT);
        }
        //3.逻辑删除部门数据
        int i = deptMapper.deleteDepts(new Date(), ids);
        if(i==0){
            throw new BusinessException(BaseResponseCode.OPERATION_ERROR);
        }
    }



}
